# -*- coding: utf-8 -*-

# 作用：用于练习Python的基本语法
# 作者：xiaopan, xpgo@163.com
# 使用：要运行某一个函数，可将本文件最后面代码改为想要运行的函数名

# Python的入门代码
print("Hello world!")


# 用于练习Python中不同的变量类型
def intro_variables():
    webpage_url = 'http://vis-www.cs.umass.edu/lfw/alpha_last_A.html'  # 字符串变量
    image_number = 100  # 整数型变量
    image_scale = 1.5  # 浮点数变量
    image_png_only = True  # 逻辑变量

    print("I will download " + str(image_number) + " images from " + webpage_url)
    print("Only download PNG images: " + str(image_png_only))
    print("The images will be scaled to " + str(image_scale) + " of original size.")

    webpage_url = 'http://www.baidu.com'
    image_number = 50
    image_scale = 0.5
    image_png_only = False

    print("I will download " + str(image_number) + " images from " + webpage_url)
    print("Only download PNG images: " + str(image_png_only))
    print("The images will be scaled to " + str(image_scale) + " of original size.")


# 用于练习字符串类型的定义方式
def string_define():
    webpage_url = 'http://www.baidu.\n com'
    webpage_description = '这是百度网址，单引号里可用"双引号"，还可以用回车符：\n，表示是新的一行。'
    image_name = "car.png"
    image_description = '''
        这是图片描述。
        这里都是字符串的内容
        可以随便换行！
    '''

    print("网页地址：" + webpage_url)
    print("网址说明：" + webpage_description)
    print("图片名称：" + image_name)
    print("图片描述：" + image_description)


# 用于练习字符串对象的函数操作、字符串子范围的选取
def string_object():
    webpage_url = 'http://www.baidu.com'
    webpage_description = '这是百度网址，单引号里可用"双引号"，还可以用回车符：\n这是新的一行。'

    url_upper = webpage_url.upper()
    url_baidu_position = webpage_url.find("baidu")
    url_length = len(webpage_url)
    url_part5 = webpage_url[0:5]
    url_head2 = webpage_url[1]
    url_last3 = webpage_url[-3:]

    print("网址：" + webpage_url)
    print("网址大写：" + url_upper)
    print("网址中baidu的位置：" + str(url_baidu_position))
    print("网址长度：" + str(url_length))
    print("网址前5个字符：" + url_part5)
    print("网址第2个字符：" + url_head2)
    print("网址最后3个字符：" + url_last3)


# 用于练习数值型变量的操作
def number_object():
    a = 3
    b = 4
    c = a * a + b * b
    pi = 3.1415926
    pi_int = int(pi)  # 转换成整数

    # 不同形式的输出
    print(a)
    print(b)
    print(c)
    print(pi)
    print(pi_int)
    print("pi = " + str(pi))
    print("pi = {:5.2f}".format(pi))  # 5位数，小数点后2位


# 用于练习列表的操作
def list_intro():
    image_names = ["image1.png", "image2.png", "image3.jpg", "image4.gif"]

    print(image_names)

    image_names.append("image5.png")
    print(image_names)

    idx = image_names.index("image2.png")
    print(idx)

    image_count = len(image_names)
    print(image_count)

    del image_names[2]
    print(image_names)

    image_names2 = ["image6.png", "image7.jpg"]
    image_names = image_names + image_names2
    print(image_names)

    image_info = ["PNG", 400, 800, True]
    print(image_info[2])


# 用于练习字典的操作
def dict_intro():
    image_info = ["image1.png", "PNG", 400, 800, True]  # 定义列表
    print(image_info[1])  # PNG
    print(image_info[-1])  # True

    image_info = {
        "name": "image1.png",
        "width": 400,
        "height": 800,
        "isPNG": True,
    }  # 定义字典

    print(image_info["name"])  # image1.png
    print(image_info["width"])  # 400
    print(image_info["isPNG"])  # True

    image_info["size"] = 1024
    print(image_info["size"])  # 1024


# 用于练习for循环的操作、判断
def intro_loop():
    # 假设已经获得了所有图片的名称
    image_names = ["image1.png", "image2.png", "image3.jpg", "image4.gif", "image5.png"]
    num_images = len(image_names)

    # 进入循环
    for image_index in range(num_images):

        # 图片的实际链接地址
        name = image_names[image_index]
        image_link = "http://vis-www.cs.umass.edu/" + name

        # 只下载PNG图片
        if name[-3:] == "png":
            print("Download image: " + image_link)


# 用于练习另一种方式的for循环
def intro_loop2():
    # 假设已经获得了所有图片的名称
    image_names = ["image1.png", "image2.png", "image3.jpg", "image4.gif", "image5.png"]

    # 进入循环
    for name in image_names:

        # 图片的实际链接地址
        image_link = "http://vis-www.cs.umass.edu/" + name

        # 只下载PNG图片
        if name[-3:] == "png":
            print("Download image: " + image_link)


# 用于练习for循环的中止
def intro_loop3():
    # 假设已经获得了所有图片的名称
    image_names = ["image1.png", "image2.png", "image3.jpg", "image4.gif", "image5.png"]
    num_images = len(image_names)

    # 进入循环
    for image_index in range(num_images):

        # 图片的实际链接地址
        name = image_names[image_index]
        image_link = "http://vis-www.cs.umass.edu/" + name

        # 控制是否终止当前步或后继所有步的循环，continue 终止当前步，break 终止后继所有步的循环
        if (image_index == 3):
            continue
            # 可以尝试将continue换成break来看差别

        # 只下载PNG图片
        if name[-3:] == "png":
            print("Download image: " + image_link)


# 用于练习while循环的操作、逻辑操作符
def intro_while():
    image_names = ["image1.png", "image2.png", "image3.jpg", "image4.gif", "image5.png"]
    image_count = 0

    while (image_count < 4):
        # 获取图片名称
        name = image_names[image_count]
        image_count = image_count + 1

        # 图片的实际链接地址
        image_link = "http://vis-www.cs.umass.edu/" + name

        # 只下载PNG和JPG图片
        if (name[-3:] == "png") or (name[-3:] == "jpg"):
            print("Download image " + str(image_count) + ": " + image_link)
        else:
            print("Cancel image " + str(image_count) + ": " + image_link)


# 用于练习while循环和输入操作
def intro_while2():
    loop_count = 1

    while True:
        user_type = input("请输入任何内容并按回车：")
        if user_type == "quit":
            print("退出循环！")
            break
        elif user_type == "help":
            print("请输入任何内容并按回车")
            print("输入 quit 停止 ")
            print("输入 help 获取帮助信息")
        else:
            print("你的输入内容是：" + user_type)


# 用于练习自定义函数文件的导入
def func_import():
    # imageFuncs.py文件中包含自定义的函数 download_images
    import imageFuncs

    image_names = [
        "image1.png",
        "image2.png",
        "image3.jpg",
        "image4.gif",
        "image5.png"]
    image_max = 4
    onlyPNG = True

    imageFuncs.download_images(image_names, image_max, onlyPNG)

    image_names_more = ["pic1.png", "pic2.png", "pic3.jpg", "pic4.gif", "pic5.png", "pic6.png"]
    image_max2 = 5
    onlyPNG = False

    imageFuncs.download_images(image_names_more, image_max2, onlyPNG)

    # 假设已经获得了所有图片的名称
    print("\nNo function call")
    image_names = ["image1.png", "image2.png", "image3.jpg", "image4.gif", "image5.png"]

    # 进入循环
    for name in image_names:

        # 图片的实际链接地址
        image_link = "http://vis-www.cs.umass.edu/" + name

        # 只下载PNG图片
        if name[-3:] == "png":
            print("Download image: " + image_link)


# 用于练习库的使用
def lib_usage():
    # 使用数学函数库
    # 导入math库，你也可以把这句放在文件最前面，就可以不用在每个函数中导入了
    import math

    a = 3
    b = 4
    c = math.sqrt(a * a + b * b)
    pi3 = math.pi / 3.0
    cos_pi3 = math.cos(pi3)
    print("pi/3 = ", pi3)
    print("cos_(pi/3) = ", cos_pi3)

    # 使用图像类库
    from PIL import Image

    aImage = Image.open("image_download/image_004.png")
    aImage = aImage.resize((180, 180), Image.ANTIALIAS)
    aImage = aImage.crop((50, 50, 130, 130))
    aImage = aImage.rotate(45)
    aImage.show()


# 用于练习numpy库的使用
def numpy_intro():
    # 导入numpy
    import numpy as np

    a = np.array([(1.5, 2, 3), (4, 5, 6)])
    print("\n Numpy Array:")
    print(a)  # 自动赋予元素实数属性
    print("a[1, 0] = " + str(a[1, 0]))

    b = [[1.5, 2, 3], [4, 5, 6]]
    print("\n Python List:")
    print(b)  # 和numpy的操作有所不同
    print("b[1][0] = " + str(b[1][0]))


# 用于练习numpy来操作数据
def numpy_data():
    # 导入numpy
    import numpy as np

    # 在20到145之间产生5个数字组成的等差数列
    time = np.linspace(20, 145, 5)
    print("\ntime = ")
    print(time)

    # 产生0~19的数列，变成5*4，然后每个元素求sin()
    data = np.sin(np.arange(20)).reshape(5, 4)
    print("\ndata = ")
    print(data)
    # 保存数据
    np.savetxt("data.txt", data, fmt='%5.2f ')  # 保存数据，设置格式

    # 导入数据
    data_import = np.loadtxt("data.txt")
    print("\ndata_import = ")
    print(data_import)


def func_call():
    def download_images(image_names, max_num=5, onlyPNG=True):
        img_num = 1
        for name in image_names:
            if onlyPNG and (name[-3:] == 'png'):
                print('Download PNG image: ' + name)
            else:
                print('Download image: ' + name)
            img_num += 1
            if img_num > max_num:
                break

    image_names = ['a1.jpg', 'a2.png', 'a3.png', 'a4.png', 'a5.gif']

    # 提供所有参数的值
    download_images(image_names, 4, False)

    # 只提供前1个参数的值，其它参数取默认值
    download_images(image_names)

    # 只提供前两个参数的值，第3个参数取默认值
    download_images(image_names, 3)

    # 跳过第2个参数，设置第3个参数的值
    download_images(image_names, onlyPNG=False)

    # 用元组的形式调用参数
    params = (image_names, 2, True)
    download_images(*params)


def func_range():
    def str_change(aStr, bStrList):
        aStr = aStr.upper()
        bStrList[1] = 'Python'
        print('aStr in str_change(): ' + aStr)
        return aStr, bStrList

    aStr = 'Hello'
    bStrList = ['World', 'Ai']

    str_change(aStr, bStrList)
    print('aStr = ' + aStr)  # 数字、字符、字符串、元组等不可变对象，在函数内改变值后，函数结束仍为原值。
    print('bStrList = ' + str(bStrList))  # 列表、字典等可变对象，在函数内改变值后，函数结束后改变值。

    rst1 = str_change(aStr, bStrList)  # 返回的变量值变了
    print(rst1)  # 返回到同一元组
    print('aStr = ' + aStr)  # 字符串变量仍不变

    rst1, rst2 = str_change(aStr, bStrList)  # 返回到两个变量中
    print('rst1 = ' + rst1)
    print('rst2 = ' + str(rst2))


# -------------------------------------------------------------
# 运行某一个函数的代码
# 1. 请修改下面的函数名
# 2. 然后点击PyCharm的运行按钮
# -------------------------------------------------------------

func_range()
